import { getEmployeeList, addEmployee, updateEmployee, deleteEmployee } from "../../api/employee";
import { getLargeProjectList } from "../../api/project";

Page({
  data: {
    employees: [],
    showModal: false,
    projectList: [],
    newEmployee: {
      id: null,
      name: '',
      subProjects: ''
    },
    selectedProject: null,
    editMode: false,
    currentEditId: null,
    isSubmitting: false
  },

  onLoad() {
    this.fetchEmployeeList();
    this.fetchProjectList();
  },

  fetchEmployeeList() {
    getEmployeeList({}).then(response => {
      if (response.code === 1) {
        this.setData({
          employees: response.data
        });
      } else {
        wx.showToast({
          title: '获取员工列表失败',
          icon: 'none'
        });
      }
    }).catch(error => {
      wx.showToast({
        title: '获取员工列表出错',
        icon: 'none'
      });
      console.error('Error fetching employee list:', error);
    });
  },

  fetchProjectList() {
    getLargeProjectList({}).then(response => {
      if (response.code === 1) {
        this.setData({
          projectList: response.data
        });
      } else {
        wx.showToast({
          title: '获取项目列表失败',
          icon: 'none'
        });
      }
    }).catch(error => {
      wx.showToast({
        title: '获取项目列表出错',
        icon: 'none'
      });
      console.error('Error fetching project list:', error);
    });
  },

  navigateToAttendance(event) {
    const { id, name } = event.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/Employee-management/per-att/per-att?id=${id}&name=${name}`
    });
  },

  navigateToSala(event) {
    const { id, name } = event.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/Employee-management/sala/sala?id=${id}&name=${name}`
    });
  },

  showAddEmployeeModal() {
    this.setData({
      showModal: true,
      editMode: false,
      newEmployee: {
        id: null,
        name: '',
        subProjects: ''
      },
      selectedProject: null
    });
  },

  showEditEmployeeModal(event) {
    const id = event.currentTarget.dataset.id;
    const employee = this.data.employees.find(emp => emp.id === id);
    this.setData({
      showModal: true,
      editMode: true,
      currentEditId: id,
      newEmployee: {
        id: employee.id,
        name: employee.name,
        subProjects: employee.subProjects
      },
      selectedProject: { name: employee.subProjects }
    });
  },

  cancelModal() {
    this.setData({
      showModal: false,
      newEmployee: {
        id: null,
        name: '',
        subProjects: ''
      },
      selectedProject: null,
      currentEditId: null,
      isSubmitting: false
    });
  },

  confirmAddOrEditEmployee() {
    const newEmployee = this.data.newEmployee;
    if (newEmployee.name && newEmployee.subProjects) {
      this.setData({ isSubmitting: true });
      if (this.data.editMode) {
        updateEmployee(newEmployee).then(response => {
          if (response.code === 1) {
            this.fetchEmployeeList();
            this.cancelModal();
            wx.showToast({
              title: '员工更新成功',
              icon: 'success'
            });
          } else {
            wx.showToast({
              title: '员工更新失败',
              icon: 'none'
            });
          }
        }).catch(error => {
          wx.showToast({
            title: '员工更新出错',
            icon: 'none'
          });
          console.error('Error updating employee:', error);
        });
      } else {
        addEmployee(newEmployee).then(response => {
          if (response.code === 1) {
            this.fetchEmployeeList();
            this.cancelModal();
            wx.showToast({
              title: '员工添加成功',
              icon: 'success'
            });
          } else {
            wx.showToast({
              title: '员工添加失败',
              icon: 'none'
            });
          }
        }).catch(error => {
          wx.showToast({
            title: '员工添加出错',
            icon: 'none'
          });
          console.error('Error adding employee:', error);
        });
      }
    } else {
      wx.showToast({
        title: '请填写所有字段',
        icon: 'none'
      });
    }
  },

  inputName(event) {
    this.setData({
      'newEmployee.name': event.detail.value
    });
  },

  onProjectChange(event) {
    const selectedIndex = event.detail.value;
    const selectedProject = this.data.projectList[selectedIndex];
    this.setData({
      selectedProject: selectedProject,
      'newEmployee.subProjects': selectedProject.name
    });
  },

  confirmDeleteEmployee() {
    let id = this.data.currentEditId;
    wx.showModal({
      title: '确认删除',
      content: '确认要删除这个员工吗？',
      success: (res) => {
        if (res.confirm) {
          deleteEmployee(id).then(response => {
            if (response.code === 1) {
              this.fetchEmployeeList();
              this.cancelModal();
              wx.showToast({
                title: '员工删除成功',
                icon: 'success'
              });
            } else {
              wx.showToast({
                title: '员工删除失败',
                icon: 'none'
              });
            }
          }).catch(error => {
            wx.showToast({
              title: '员工删除出错',
              icon: 'none'
            });
            console.error('Error deleting employee:', error);
          });
        }
      }
    });
  }
});
